package org.nf.mvc.view;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.nf.mvc.servlet.View;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * @Author : LLH
 * @create 2021/5/28
 */
public class JsonView extends View {

    private Object data;
    private String pattern;

    public JsonView(Object data) {
        this.data = data;
    }

    public void setDateFormat(String pattern) {
        this.pattern = pattern;
    }

    /**
     * 响应Json数据
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void response() throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        String json=null;
        if(pattern!=null){
            Gson gson = new GsonBuilder().setDateFormat(pattern).create();
            json=gson.toJson(data);
        }else{
            json=new Gson().toJson(data);
        }
        response.getWriter().print(json);
    }
}
